import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/yhpc/YhpcViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/bean/FileUpLoadBean.dart';
import 'package:flutter_ahj_app/base/bean/flutter_AMapLocation_map.dart';
import 'package:flutter_ahj_app/base/utils/HttpUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/date_util.dart';
import 'package:flutter_ahj_app/base/utils/image_picked.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/utils/permission/SelectPicUtils.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/utils/date_util.dart';
import '../../../base/utils/video_player_page.dart';

class YhzlpdView extends BaseStatefulWidget {
  final String id;
  YhzlpdView({this.id});

  @override
  State<StatefulWidget> initState() {
    return YhzlpdViewState();
  }
}

class YhzlpdViewState extends BaseState<YhpcViewModel, YhzlpdView> {

  TextEditingController _pdjgsmCtr = TextEditingController(); // 判定结果说明
  TextEditingController _pcdxCtr = TextEditingController(); // 排查对象
  TextEditingController _pcxCtr = TextEditingController(); // 排查项
  TextEditingController _pcnrCtr = TextEditingController(); // 排查内容
  TextEditingController _yhcsCtr = TextEditingController(); // 隐患场所
  TextEditingController _yhlbCtr = TextEditingController(); // 隐患类别

  String _pcdxId = '';
  String _selOrgCode = '';
  String _selPersonOpenId = '';
  String _selRiskPointId = '';
  String _selDangerSourceId = '';
  String _selRiskDangerSourceEvaluateId = '';
  String _selHazardCategoryId = '';

  TextEditingController _zrrCtr = TextEditingController(); // 责任人
  TextEditingController _yhzrbmCtr = TextEditingController(); // 隐患责任部门

  String _selPdjg = 'notHazard';


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(!StringUtils.isEmpty(widget.id)) {
      _initData();
    }
  }

  _initData() {
    viewModel.yhzlListDetail(widget.id);
    viewModel.yhzlListDetailStream().listen((event) {
      if (event['code'] == '0') {
        setState(() {
          var _dataM = event['data'];
          _pcdxCtr.text = StringUtils.getStr(_dataM['riskPointName']);
          _selRiskPointId =  StringUtils.getStr(_dataM['riskPointId'].toString());
          _pcdxId = StringUtils.getStr(_dataM['riskPointId'].toString());

          _selDangerSourceId = StringUtils.getStr(_dataM['dangerSourceId'].toString());
          _selRiskDangerSourceEvaluateId = StringUtils.getStr(_dataM['riskDangerSourceEvaluateId'].toString());
          _pcnrCtr.text = StringUtils.getStr(_dataM['controlMeasure']);
          _yhcsCtr.text = StringUtils.getStr(_dataM['riskPointDistrictName']);

          _pcxCtr.text = StringUtils.getStr(_dataM['dangerSourceName']);
          _yhlbCtr.text =  StringUtils.getStr(_dataM['hazardCategoryName']);
          _selHazardCategoryId =  StringUtils.getStr(_dataM['hazardCategoryId'].toString());
          _yhzrbmCtr.text =  StringUtils.getStr(_dataM['riskPointOrgCodeName']);
          _selOrgCode =  StringUtils.getStr(_dataM['rectifyResponsibleOrgCode'].toString());
          _zrrCtr.text = StringUtils.getStr(_dataM['verifierName']);
          _selPersonOpenId = StringUtils.getStr(_dataM['verifierOpenId'].toString());
        });
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }




  @override
  Widget initWidget() {
    return Scaffold(
      backgroundColor: Color(0xfff4f5f6),
      appBar: MTopBar(
        elevation: 0,
        title: '判定',
      ).create(),
      body: _bodyView(),
    );
  }

  _bodyView() {
    return Container(
      child: Column(
        children: [
          Expanded(
            child: Container(
              margin: EdgeInsets.all(15),
              decoration: BoxDecoration(
                  borderRadius: new BorderRadius.all(Radius.circular(6.0)),
                  color: SQColor.white),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
                      child: Column(
                        children: [
                          Container(
                            child: Row(
                              children: [
                                JText(
                                  '* ',
                                  color: SQColor.red,
                                ),
                                Container(
                                  child: JText('隐患判定结果'),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 10),
                            child: Row(
                              children: [
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selPdjg = 'notHazard';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color: _selPdjg == 'notHazard'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                          BorderRadius.circular(8)),
                                      child: JText('不是隐患',
                                          color: _selPdjg == 'notHazard'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selPdjg = 'hazard';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color: _selPdjg == 'hazard'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                          BorderRadius.circular(8)),
                                      child: JText('是隐患',
                                          color: _selPdjg == 'hazard'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    _selPdjg == 'notHazard' ?
                    _commField(
                      isMust: true,
                      controller: _pdjgsmCtr,
                      title: '判定结果说明',
                      hintText: '请输入判定结果说明',
                      maxLength: 200,
                    ) : _yborzdView(),
                    Container(
                      height: 20,
                    ),
                  ],
                ),
              ),
            ),
          ),
          _bottomView()
        ],
      ),
    );
  }

  _yborzdView() {
    return Column(children: [
      _commField(
        controller: _pdjgsmCtr,
        title: '判定结果说明',
        hintText: '请输入判定结果说明',
        maxLength: 200,
      ),
      _commField(
          isMust: true,
          title: '排查对象',
          controller: _pcdxCtr,
          hintText: '请选择排查对象',
          isReadOnly: true,
          suffixIcon: Icon(
            Icons.arrow_forward_ios_outlined,
            size: Dimens.dimens15,
            color: SQColor.black_999999,
          ),
          onTap: () {
            Navigator.pushNamed(context, '/ChoosePcdxView')
                .then((value) {
              if (value != null) {
                Map map = value;
                _pcdxId = map['id'].toString();
                _pcdxCtr.text = map['riskPointName'];
                _yhzrbmCtr.text = map['orgName'];
                _selRiskPointId = map['id'].toString();
                _selOrgCode = map['orgCode'].toString();
                _yhcsCtr.text = map['districtName'];
              }
            });
          }),
      _commField(
          isMust: true,
          title: '排查项',
          hintText: '请选择排查项',
          controller: _pcxCtr,
          isReadOnly: true,
          suffixIcon: Icon(
            Icons.arrow_forward_ios_outlined,
            size: Dimens.dimens15,
            color: SQColor.black_999999,
          ),
          onTap: () {
            if (_pcdxCtr.text.isEmpty) {
              ToastUtils.showToast('请先选择排查对象');
              return;
            }
            Navigator.pushNamed(context, '/ChoosePcxView',
                arguments: _pcdxId)
                .then((value) {
              if (value != null) {
                Map map = value;
                _pcxCtr.text = map['dangerSourceName'];
                _selDangerSourceId =
                    map['dangerSourceId'].toString();
                _selRiskDangerSourceEvaluateId =
                    map['riskDangerSourceEvaluateId'].toString();
                _pcnrCtr.text = map['controlMeasureList'][0];

              }
            });
          }),
      _commField(
        isMust: true,
        title: '排查内容',
        controller: _pcnrCtr,
        hintText: '请选择排查内容',
        isReadOnly: true,
      ),
      _commField(
          isMust: false,
          title: '隐患所在场所/位置',isEdit: true,
          hintText: '',
          isReadOnly: true,
          controller: _yhcsCtr),
      _commField(
          isMust: true,
          title: '隐患类别',
          hintText: '请选择隐患类别',
          isReadOnly: true,
          controller: _yhlbCtr,
          suffixIcon: Icon(
            Icons.arrow_forward_ios_outlined,
            size: Dimens.dimens15,
            color: SQColor.black_999999,
          ),
          onTap: () {
            Navigator.pushNamed(context, '/ChooseYhlbView')
                .then((value) {
              if (value != null) {
                Map map = value;
                _selHazardCategoryId = map['id'].toString();
                _yhlbCtr.text = map['category'];
              }
            });
          }),
      _commField(
          title: '隐患责任部门',
          controller: _yhzrbmCtr, isEdit: true,
          hintText: '',
          isReadOnly: true,),
      _commField(
          isMust: true,
          title: '核查人',
          hintText: '请选择核查人',
          controller: _zrrCtr,
          isReadOnly: true,
          suffixIcon: Icon(
            Icons.arrow_forward_ios_outlined,
            size: Dimens.dimens15,
            color: SQColor.black_999999,
          ),
          onTap: () {
            Navigator.pushNamed(context, '/ChoosePersonDan',
                arguments: '')
                .then((value) {
              if (value != null) {
                Map map = value;
                _selPersonOpenId = map['openId'];
                _zrrCtr.text = map['name'];
              }
            });
          }),
    ],);
  }


  _bottomView() {
    return Row(
      children: [
        Expanded(
          child: InkWell(
            onTap: () {
              _done();
            },
            child: SafeArea(
              child: Container(
                margin: EdgeInsets.only(left: 15, right: 15),
                height: 45,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: SQColor.theme_color,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: JText('确定', color: Colors.white),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 提交保存
  _done() {
    if(_selPdjg == 'notHazard') {
      if(_pdjgsmCtr.text.isEmpty) {
        ToastUtils.showToast('请填写判定结果说明');
        return;
      }
    }else{
      if(_pcdxCtr.text.isEmpty) {
        ToastUtils.showToast('请选择排查对象');
        return;
      }
      if(_pcxCtr.text.isEmpty) {
        ToastUtils.showToast('请选择排查项');
        return;
      }
      if(_pcnrCtr.text.isEmpty) {
        ToastUtils.showToast('请填写排查内容');
        return;
      }

      if(_selHazardCategoryId.isEmpty) {
        ToastUtils.showToast('请选择排查类别');
        return;
      }
      if(_selPersonOpenId.isEmpty) {
        ToastUtils.showToast('请填写核查人');
        return;
      }

    }
    _submit();
  }

  _submit() {
    var map = {
      'hazardId': widget.id,
      'determineResultType': _selPdjg,
      'determineResultDescription': _pdjgsmCtr.text,
      'riskPointId': _selRiskPointId,
      'dangerSourceId' : _selDangerSourceId,
      'riskDangerSourceEvaluateId': _selRiskDangerSourceEvaluateId,
      'controlMeasure': _pcnrCtr.text,
      'hazardCategoryId': _selHazardCategoryId,
      'verifierOpenId' : _selPersonOpenId,
    };
    ToastUtils.showLoading();
    viewModel.yhpd(map);
    viewModel.yhpdDataStream().listen((event) {
      ToastUtils.dissLoading();
      if (event['code'] == '0') {
        ToastUtils.showToast('提交成功');
        Navigator.of(context)..pop()..pop();
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      ToastUtils.dissLoading();
      print(e);
    });
  }

  _commField(
      {bool isMust = false,
        String hintText = '',
        Widget suffixIcon,
        String title = '',
        bool isReadOnly = false,
        int maxLength, bool isEdit = false,//是否可编辑
        var onTap,
        var controller}) {
    return Container(
      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
      child: Column(
        children: [
          Container(
            child: Row(
              children: [
                isMust
                    ? JText(
                  '* ',
                  color: SQColor.red,
                )
                    : Container(),
                Container(
                  child: JText(title),
                ),
              ],
            ),
          ),
          Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 10),
            padding: EdgeInsets.only(
                left: 10,
                right: maxLength == null ? 0 : 10,
                bottom: maxLength == null ? 0 : 10),
            child: TextField(
              controller: controller,
              onTap: onTap,
              maxLength: maxLength,
              readOnly: isReadOnly,
              style: TextStyle(fontSize: Dimens.textSize28),
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: hintText,
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  suffixIcon: suffixIcon),
            ),
            decoration: BoxDecoration(
              color: isEdit ? SQColor.lineE7E7E7 : SQColor.white,
              border: Border.all(
                width: 1,
                color: SQColor.lineE7E7E7,
              ),
              borderRadius: BorderRadius.all(Radius.circular(Dimens.dimens4)),
            ),
          ),
        ],
      ),
    );
  }
}
